using Consul;
using J.Status;
using J.Status.Extensions;
using J.StatusRepository;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using NLog.Web;
using System.Reflection;
using System.Text;



internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        //注入上下文
        builder.Services.AddDbContext<MyDbContext>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("ConnStr")));
        //异常过滤器
        builder.Host.UseNLog();
        //全局异常过滤器
        builder.Services.AddControllers(x => x.Filters.Add<MyExceptionFilter>());

        //注入Hangfire
        //builder.Services.AddControllersWithViews();
        //builder.Services.AddHangfire(configuration => configuration
        //    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
        //    .UseSimpleAssemblyNameTypeSerializer()
        //    .UseRecommendedSerializerSettings()
        //    .UseSqlServerStorage(builder.Configuration.GetConnectionString("ConnStr")));

        //builder.Services.AddHangfireServer();


        //注入仓储服务
        builder.Services.AssessGet();
        //注入autoMapper
        builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        //注入中介者
        builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

        builder.Services.AddControllers();
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen(x =>
        {
            //Swagger中文注释
            var xml = AppDomain.CurrentDomain.BaseDirectory + "J.Status.xml";
            x.IncludeXmlComments(xml, true);
        });

        //jwt
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                        .AddJwtBearer(options =>
                        {
                            //取出私钥
                            var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                            options.TokenValidationParameters = new TokenValidationParameters()
                            {
                                //验证发布者
                                ValidateIssuer = true,
                                ValidIssuer = builder.Configuration["Authentication:Issuer"],
                                //验证接收者
                                ValidateAudience = true,
                                ValidAudience = builder.Configuration["Authentication:Audience"],
                                // 验证是否过期
                                ValidateLifetime = true,
                                // 验证私钥
                                IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                            };
                        });

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        //if (app.Environment.IsDevelopment())
        //{
        //app.UseExceptionHandler("/Home/Error");
        //// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        //app.UseHsts();


        app.UseSwagger();
        app.UseSwaggerUI();
        //}
        //跨域
        app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        // 默认情况下，仅允许本地访问 Hangfire 仪表板。必须配置仪表板授权才能允许远程访问
        // 这里添加了一个连接地址，表明使用新的地址进行访问，而不是默认地址。
        //默认地址是hangfire
        //app.UseHangfireDashboard("/dashboard");
        //app.UseRouting();

        app.UseStaticFiles();

        app.UseAuthentication();//身份认证
        app.UseAuthorization();//授权

        RegisterConsul();
        app.MapControllers();

        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapControllers();
        //    endpoints.MapDefaultControllerRoute();
        //    // Map hangfire的端点
        //    endpoints.MapHangfireDashboard();
        //});

        //定时作业
        //RecurringJob.AddOrUpdate<TimeService>(x => x.UpdateState(), "41 08 * * *");


        app.Run();






        ///<summary>
        ///注册consul服务
        ///</summary>
        static void RegisterConsul()
        {
            var consulClient = new ConsulClient(p => { p.Address = new Uri($"http://10.31.56.23:8500"); });//请求注册的Consul地址（不动）
                                                                                                           //这里的这个ip就是本机的ip，这个端口8500这个是默认注册服务端口
            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//间隔固定的时间访问一次，https://localhost:44308/api/Health
                HTTP = $"http://10.31.56.22:8880/WeatherForecast",//健康检查地址放（发布地址）WeatherForecast不要动就改ip加端口号
                Timeout = TimeSpan.FromSeconds(5)
            };

            var registration = new AgentServiceRegistration()
            {
                Checks = new[] { httpCheck },
                ID = Guid.NewGuid().ToString(),
                Name = "Status",//服务名称项目名称
                Address = " http://10.31.56.22:8880/swagger/index.html",//改成发布地址
                Port = 8880,//服务端口（）
            };
            consulClient.Agent.ServiceRegister(registration).Wait();//注册服务
                                                                    //consulClient.Agent.ServiceDeregister(registration.ID).Wait();//registration.ID是guid
                                                                    //当服务停止时需要取消服务注册，不然，下次启动服务时，会再注册一个服务。
                                                                    //但是，如果该服务长期不启动，那consul会自动删除这个服务，大约2，3分钟就会删了
        }
    }
}